package dvsdk.rest;

import com.google.gson.Gson;
import com.sun.jersey.api.client.ClientResponse;
import db.BeanTransFullTable;
import db.BeanTransTable;
import dvsdk.GlobalConfig;
import dvsdk.client.MulisTable;
import dvsdk.util.Util;
import dvsdk.util.UtilWeb;
import java.util.Iterator;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Providers;
import usr.BeanTransAgent;
import usr.BeanTransUser;

/**
 *
 * @author Develop
 */
public class ExternalWorker implements Runnable {

    private Thread thread;
    private IWorker worker;
    private int cur_i=0,cur_j=0;

    public ExternalWorker(IWorker worker) {
        this.worker = worker;
        int cur_t=GlobalConfig.getCore().getCurrentIntFrame();
        this.cur_i=cur_t/10%10-1;
        this.cur_j=cur_t/10-1;
        init();
    }

    private void init() {
        thread = new Thread(this);
        thread.setName("ExternalWorker");
        thread.start();
    }

    public void stop() {
        if (thread != null) {
            thread.stop();
        }
    }
    @Context
    Providers ps;

    @Override
    public void run() {
        worker.reset();
        BeanTransAgent bta = UtilWeb.getTransportAgent();
        worker.max_global(3);
        worker.max_group(1);
        worker.max_work(1);

        worker.println("["+Util.getCurDate()+"] Инициализация подключения");
        try {
            NewJerseyClient client = new NewJerseyClient(GlobalConfig.GLOBAL_MULIS_SERVER_PATH_USER);
            client.setUsernamePassword(GlobalConfig.MASTER_INN_GLOBAL, GlobalConfig.MASTER_PWD_MD5);
            
            ClientResponse response = client.getWebResource().head();
            int statusCode = response.getStatus();
            worker.println("["+Util.getCurDate()+"] CODE: "+statusCode);
            worker.println("["+Util.getCurDate()+"] Синхронизация пользователей");
            Gson gson = new Gson();
            client.putJson(gson.toJson(bta)); worker.inc_work(); worker.inc_group();
            //worker.reset_work();
            //worker.reset_group();
            worker.inc_global();
            
            
            worker.reset_work();
            worker.reset_group();
            worker.println("["+Util.getCurDate()+"] Синхронизация агентств");
            client.changePath(GlobalConfig.GLOBAL_MULIS_SERVER_PATH_AGENT);
            client.getState(); worker.inc_work(); worker.inc_group();
            //worker.reset_work();
            //worker.reset_group();
            worker.inc_global();
            
            
            worker.println("["+Util.getCurDate()+"] Синхронизация объявлений");
            client.changePath(GlobalConfig.GLOBAL_MULIS_SERVER_PATH_BASE);
            int i=0; int ar[]; worker.max_group(Util.F_SALE_ARR.length+Util.F_RENT_ARR.length);
            worker.max_work(bta.getAgents().size());
            while (i<=1) {
                switch (i) {
                    case 0: default: ar=Util.F_SALE_ARR; break;
                    case 1: ar=Util.F_SALE_ARR; break;
                }
                for (int num : ar) {
                    worker.reset_work();
                    GlobalConfig.getCore().setCurrentTab(i, num);
                    MulisTable table = GlobalConfig.getCore().getCurrentTable();
                    worker.println(table.getName());

                    for (Iterator<BeanTransUser> it = bta.getAgents().iterator(); it.hasNext();) {
                        BeanTransUser user = it.next();
                        
                        client.changePath(GlobalConfig.GLOBAL_MULIS_SERVER_PATH_BASE);
                        //BeanTransTable btt = UtilWeb.getTransportTable(worker.getCore().getBase(table.getName()), table.getName(), "state=1 AND idr='"+user.getIdr()+"'", bta.getIda(), user.getIdr());
                        //client.putJson(gson.toJson(btt));
                        String ids=client.getState();
                        worker.println(ids);
                        
                        client.changePath(GlobalConfig.GLOBAL_MULIS_SERVER_PATH_FULL_BASE);
                        BeanTransFullTable btft = UtilWeb.getTransportTableFull(GlobalConfig.getCore().getBase(table.getName()), table.getName(), "state=1 AND idr='"+user.getIdr()+"' AND id IN("+ids+")",table.getSqlParams(), bta.getIda(), user.getIdr());
                        client.putJson(gson.toJson(btft));
                        
                        worker.inc_work();
                        
                    }
                    worker.inc_group();
                }
                i++;
            }
            //worker.reset_work();
            worker.inc_global();

            
            
           
            //worker.println(); worker.inc();
            //MessageBodyWriter uw = ps.getMessageBodyWriter(BeanUser.class, BeanUser.class, new Annotation[0], MediaType.APPLICATION_JSON_TYPE);
            /*for (Iterator<BeanTransUser> it = bta.getAgents().iterator(); it.hasNext();) {
                BeanTransUser beanUser = it.next();
                worker.print(beanUser.getIdr());
                Gson gson = new Gson();
                client.putJson(gson.toJson(beanUser));
                worker.inc_work();
                worker.println(" - " + client.getState() + "; ");
            }
            worker.print("\n");*/

            worker.println("["+Util.getCurDate()+"] Синхронизация завершена\n");
            client.close();
            GlobalConfig.getCore().setCurrentTab(cur_i, cur_j);
            worker.complite();
        } catch (Exception ex) {
            if (ex.getMessage().endsWith(" 401")) {
                worker.println("["+Util.getCurDate()+"] Ошибка при авторизации на центральном сервере");
            } else {
                worker.println("["+Util.getCurDate()+"] Ошибка на центральном сервере: " + ex.getLocalizedMessage());
            }
            ex.printStackTrace();
        }

    }
}
